<script setup lang="ts">
import { getCurrentInstance, ref, reactive, onBeforeMount, onMounted } from 'vue'
import { onBeforeRouteLeave } from 'vue-router'
const { proxy } = getCurrentInstance()

/* ---- */
const userInfo = proxy.$Store.get('userInfo') || {}
const logUser = proxy.$Store.get('logUser') || {}
const WXConfig = proxy.$Store.get('WXConfig') || {}
const forSys = proxy.$Sys || []

/* --设置微信分享功能-- */
proxy.$WxTool.loadJsdk(WXConfig, (obj) => {
  if (!obj) return
  // ----
  obj.hideMenuItem()
})

/* ---- */
let myCityData = []
// ----
const advs = reactive({
  add: true,
  maxnum: 0,
  forFree: 1,
  setTrueStyle: {},
  imgs: [],
  option: {
    viewMode: 0,
    dragMode: 'move',
    autoCropArea: 1,
    center: false,
    cropBoxMovable: false,
    cropBoxResizable: false,
    toggleDragModeOnDblclick: false
  },
  cropImg: proxy.$Global.cropImg
})
// ----
const isMobile = /^(1[3456789]\d{9})$/
const form = reactive({
  tabName: 'market_capital',
  status: 0,
  // ----
  company: '',
  leader: '',
  sex: 1,
  telphone: '',
  remark: '',
  addrCity: ''
})

/* ---- */
const pickerCity = ref()
const uploadoss = ref()
const layer = ref()
const layerLoading = ref()

/* ---- */
const setPublicInfo = async (item, callback) => {
  await proxy.$http[item.type](item.url, item.data).then((res) => {
    if (res) callback && callback(res)
  }).catch((err) => { proxy.$Myfun.forToast(layer.value, 'open', err) })
}
// ----
const initData = () => {
  const cityItems = []
  proxy.$City.forEach((item, index) => {
    cityItems.push({
      value: String(item.value),
      text: proxy.$Myfun.setText(item.text)
    })
  })
  myCityData = cityItems
}
// ----
const getFormInfo = async () => {
  advs.setTrueStyle = { height: `${document.querySelector('.squareBox dl dd label').clientWidth / advs.forFree}px` }
  // -- 获取招商招聘设置信息 --
  const newItems = forSys.filter((item) => { return String(item.name) === form.tabName })
  if (Number(newItems.length) === 1) {
    proxy.$Myfun.getJsonData(newItems[0].value, (resJson) => {
      const RJData = resJson[0] || {}
      // ----
      if (({}).hasOwnProperty.call(RJData, 'coop_status')) form.status = RJData.coop_status
    })
  }
  // -- 获取动态信息 --
  if (proxy.$route.query.id) {
    const forCapitalData = { params: { 'TeamsSearch[id]': proxy.$route.query.id } }
    await proxy.$Axios.all([
      proxy.$Axios.get('teams/index', forCapitalData)
    ]).then(proxy.$Axios.spread((capitalData) => {
      const CData = capitalData.items[0] || {}
      // ----
      form.company = CData.name
      form.leader = CData.leader
      if (Number(CData.gender) > 0) form.sex = CData.gender
      form.telphone = CData.telphone
      form.remark = CData.introduce
      // ----
      const forCity = CData.citys.split(',')
      form.addrCity = forCity[1]
      // ----
      proxy.$Myfun.getJsonData(CData.img_json, (resJson) => {
        resJson.forEach((item) => {
          advs.imgs.push({
            imgName: item.name,
            imgUrl: item.image,
            imgW: item.width,
            imgH: item.height
          })
        })
        if (Number(advs.imgs.length) >= Number(advs.maxnum) && Number(advs.maxnum) > 0) advs.add = !advs.add
      })
    })).catch((err) => { proxy.$Myfun.forToast(layer.value, 'open', err) })
  }
  // ----
  document.querySelectorAll('.form-sex input[type="radio"]').forEach((item) => {
    if (Number(item.value) === Number(form.sex)) document.querySelector('.form-sex label[for="' + item.getAttribute('id') + '"]').querySelector('b').setAttribute('class', 'fa fa-dot-circle xw-color-12')
  })
}
// --上传图片操作--
const uploadAct = (type, selectObj, event, index) => {
  const uploadOss = uploadoss.value
  switch (Number(type)) {
    case 1: {
      uploadOss.uploadImg(event, selectObj,'imgs', index)
      break
    }
    case 2: {
      uploadOss.delInfo(selectObj, event)
      break
    }
    case 3: {
      uploadOss.uploadImgMoreWX(selectObj)
      break
    }
  }
}
// ----
const emptyInfo = (event) => {
  const curEL = event.currentTarget
  const input = curEL.parentElement.querySelector('input')
  input.value = ''
  input.dispatchEvent(new Event('input'))
}
// ----
const getAuditFun = (type, item) => {
  switch (Number(type)) {
    case 1: {
      const curEL = item.currentTarget
      const parentEL = curEL.parentElement
      // ----
      parentEL.querySelectorAll('label').forEach((curItem) => { curItem.querySelector('b').setAttribute('class', 'fal fa-circle xw-color-16') })
      curEL.querySelector('b').setAttribute('class', 'fa fa-dot-circle xw-color-12')
      break
    }
    case 3: {
      const options = {
        type: 1,
        button: ['取消', '确定'],
        initData: myCityData,
        yes: (result) => {
          let resText = ''
          result.forEach((curItem, index) => {
            resText += (index > 0 ? ' - ' : '') + curItem.text
          })
          form.addrCity = resText
        }
      }
      proxy.$Myfun.isIndepth(pickerCity.value, 'open', options)
      break
    }
  }
}
const subform = async () => {
  if (Number(form.company.length) === 0) {
    proxy.$Myfun.forToast(layer.value, 'open', '请填写企业名称！')
    return false
  }
  if (Number(form.telphone.length) > 0 && !isMobile.test(form.telphone)) {
    proxy.$Myfun.forToast(layer.value, 'open', '请填写合法的手机号！')
    return false
  }
  if (Number(form.addrCity.length) === 0) {
    proxy.$Myfun.forToast(layer.value, 'open', '请选择所属地区！')
    return false
  }
  // ----
  let forAdvs = ''
  if (Number(advs.imgs.length) > 0) {
    const advItems = []
    advs.imgs.forEach((item, index) => {
      advItems.push({
        name: item.imgName,
        image: item.imgUrl,
        width: item.imgW,
        height: item.imgH
      })
    })
    forAdvs = JSON.stringify(advItems)
  }
  // ----
  let forType = 'post'
  let forUrl = 'teams/create'
  let forData = {
    
    type: 2,
    // --默认审核状态--
    status: form.status,
    // ----
    name: form.company,
    leader: form.leader,
    gender: form.sex,
    telphone: form.telphone,
    introduce: form.remark,
    citys: ',' + form.addrCity + ',',
    img_json: forAdvs,
    // ----
    config_id: userInfo.config_id,
    openid: userInfo.openid
  }
  if (proxy.$route.query.id) {
    forType = 'patch'
    forUrl = 'teams/update?id=' + proxy.$route.query.id
    forData = {
      name: form.company,
      leader: form.leader,
      gender: form.sex,
      telphone: form.telphone,
      introduce: form.remark,
      citys: ',' + form.addrCity + ',',
      img_json: forAdvs,
      // ----
      config_id: userInfo.config_id,
      openid: userInfo.openid
    }
  }
  // ----
  proxy.$Myfun.onLoading(layerLoading.value, 'open', proxy.$Global.loadingMsg)
  let resData = ''
  await proxy.$http[forType](forUrl, forData).then((res) => { resData = res }).catch((err) => { proxy.$Myfun.forToast(layer.value, 'open', err) })
  // ----
  proxy.$Myfun.disLoading(layerLoading.value, 'close')
  if (resData) {
    if (proxy.$route.query.id) {
      proxy.$router.back()
    } else {
      proxy.$Myfun.forToast(layer.value, 'open', '信息提交成功，请等待洽谈合作。', () => { proxy.$router.back() })
    }
  }
}
const goback = () => { proxy.$router.back() }

/* ---- */
onBeforeMount(() => {
  initData()
})
onMounted(() => {
  getFormInfo()
})
onBeforeRouteLeave(() => { proxy.$Myfun.setScrollTop(proxy.$refs.formSection) })
</script>

<template>
  <div class="mescroll-touch" ref="formSection">
    <div class="formSet">
      <ul>
        <li>
          <div class="form-are xw-radius-3">
            <h1>标题名称</h1>
            <p><textarea class="tarea-H3" placeholder="" v-model.trim="form.company"></textarea></p>
          </div>
        </li>
        <li>
          <div class="form-txt xw-radius-3 xw-flex xw-flex-align">
            <i>业务负责</i>
            <p class="xw-flex-W1"><input class="text" type="text" placeholder="请填写业务负责人姓名" v-model.trim="form.leader"/></p>
            <transition name="fade"><em class="fa fa-times-circle" @click="emptyInfo" v-if="form.leader"></em></transition>
          </div>
        </li>
        <li>
          <div class="form-txt xw-radius-3 xw-flex xw-flex-align">
            <i>性别属性</i>
            <p class="xw-flex-W1"></p>
            <div class="form-sex xw-flex xw-flex-align">
              <input type="radio" id="male" value="1" v-model="form.sex"/>
              <input type="radio" id="female" value="2" v-model="form.sex"/>
              <label for="male" class="xw-flex xw-flex-align" @click="getAuditFun(1, $event)"><b class="fal fa-circle xw-color-16"></b>男</label>
              <label for="female" class="xw-flex xw-flex-align" @click="getAuditFun(1, $event)"><b class="fal fa-circle xw-color-16"></b>女</label>
            </div>
          </div>
        </li>
        <li>
          <div class="form-txt xw-radius-3 xw-flex xw-flex-align">
            <i>联系电话</i>
            <p class="xw-flex-W1"><input class="text" placeholder="" v-model.trim="form.telphone"/></p>
            <transition name="fade"><em class="fa fa-times-circle" @click="emptyInfo" v-if="form.telphone"></em></transition>
          </div>
        </li>
        <li>
          <div class="form-txt xw-radius-3 xw-flex xw-flex-align">
            <i>所属区域</i>
            <p class="xw-flex-W1"><input class="text" type="text" placeholder="" v-model="form.addrCity" @click="getAuditFun(3)" readonly unselectable="on" onfocus="this.blur()"/></p>
            <span class="fa fa-caret-down xw-color-16"></span>
            <transition name="fade"><em class="fa fa-times-circle" @click="emptyInfo" v-if="form.addrCity"></em></transition>
          </div>
        </li>
        <li>
          <div class="form-are xw-radius-3">
            <h1>服务内容</h1>
            <p><textarea class="tarea-H3" placeholder="" v-model.trim="form.remark"></textarea></p>
          </div>
        </li>
        <li>
          <div class="form-imgs xw-radius-3 squareBox">
            <div class="FIS-top xw-flex xw-flex-align xw-flex-justify">
              <span class="FIS-title">图片展示</span>
              <span v-if="Number(advs.maxnum) > 0">数量：最多{{advs.maxnum}}张</span>
            </div>
            <dl class="FIS-img xw-float">
              <dd class="xw-float-W3" v-for="(item, index) in advs.imgs"><label class="xw-block xw-act" :style="advs.setTrueStyle"><div class="xw-bgImg" :style="{ backgroundImage: 'url(' + item.imgUrl + ')' }"></div><input type="file" style="display: none;" accept="image/*" @change="uploadAct(1, advs, $event, index)"/></label><span class="FIS-del fal fa-times xw-act" @click="uploadAct(2, advs, index)"></span></dd>
              <dd class="xw-float-W3" v-if="advs.add"><label class="xw-act xw-flex xw-flex-center" :style="advs.setTrueStyle" @click="uploadAct(3, advs)"><em class="fal fa-plus"></em></label></dd>
            </dl>
          </div>
        </li>
      </ul>
      <div class="form-sub xw-radius-3 xw-bgCL-11 xw-act" @click="subform">确定提交</div>
      <div class="form-sub xw-radius-3 xw-WhiteRed xw-act" @click="goback">取消返回</div>
    </div>
    <picker-view ref="pickerCity"/>
    <uploadoss-view ref="uploadoss"/>
    <layer-view ref="layer"/>
    <layer-view ref="layerLoading"/>
  </div>
</template>